package cn.cas.mango.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.mongodb.client.MongoClients;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;

@Configuration
public class Config {

  @Value("${elasticsearch.host}")
  private String host;

  @Value("${elasticsearch.port}")
  private int port;

  @Value("${elasticsearch.username:-}")
  private String username;

  @Value("${elasticsearch.password:-}")
  private String password;

  @Value("${mongodb.url}")
  private String mongoDbUrl;

  @Value("${mongodb.dataBaseName}")
  private String mongoDatabaseName;

  private final int TIME_OUT = 300000;

  /**
   * elasticsearch client.
   */
  @Bean
  public ElasticsearchClient elasticsearchClient() {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
        new UsernamePasswordCredentials(username, password));
    RestClient restClient;
    if ("-".equals(username)) {
      restClient = RestClient.builder(new HttpHost(host, port)).build();
    } else {
      restClient = RestClient.builder(new HttpHost(host, port))
          .setHttpClientConfigCallback(
              httpClientBuilder -> httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().
                      //超时时间5分钟
                  setConnectTimeout(TIME_OUT)
                  //这就是Socket超时时间设置
                  .setSocketTimeout(TIME_OUT)
                  .setConnectionRequestTimeout(TIME_OUT).build()).setDefaultCredentialsProvider(
                  credentialsProvider))
          .build();
    }
    ElasticsearchTransport transport =
        new RestClientTransport(restClient, new JacksonJsonpMapper());
    return new ElasticsearchClient(transport);
  }

  @Bean
  public MongoTemplate mongoTemplate() {
    return new MongoTemplate(MongoClients.create(mongoDbUrl), mongoDatabaseName);
  }
}
